#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import shutil
from PIL import Image, ImageSequence, ImageDraw, ImageFont

bak = f"{os.getcwd()}\\tmp\\bak"
yige = f"{os.getcwd()}\\tmp\\yige"
face = f"{os.getcwd()}\\tmp\\face"
facewx = f"{os.getcwd()}\\tmp\\facewx"
facewxs = f"{os.getcwd()}\\tmp\\facewxs"
os.makedirs(f"{bak}",exist_ok=True)
os.makedirs(f"{yige}",exist_ok=True)
os.makedirs(f"{face}",exist_ok=True)
os.makedirs(f"{facewx}",exist_ok=True)
os.makedirs(f"{facewxs}",exist_ok=True)

def generate_wx_author():
    # 微信艺术家
    for file in os.listdir(f"{yige}"):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x==1024:
                print(file)
                base = im.copy().resize((640,640)).convert('RGB')
                base.save(f"{yige}\\{file}.640x640.jpg")
                break #一个就够了

def generate_wxface():
    #微信封面图
    for file in os.listdir(f"{yige}"):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x== 2048:
                im = im.copy().resize((1280,720))
                x,y = im.size
            if x==1280:
                print(file)
                base = im.copy().crop((0, 0, 1280, 683)).resize((750,400)).convert('RGB')
                base.save(f"{yige}\\{file}.750x400.jpg")
    # 微信引导图
    for file in os.listdir(f"{yige}"):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x== 2048:
                im = im.copy().resize((1280,720))
                x,y = im.size
            if x==1280:
                print(file)
                base = im.copy().crop((140, 0, 996+140, 720)).resize((750,560)).convert('RGB')
                base.save(f"{yige}\\{file}.750x560.gif",quality=10,subsampling=0)
                os.system(f"gifsicle --colors=16 {yige}\\{file}.750x560.gif -o {yige}\\{file}.750x560.small.gif")
    # 压缩 .\gifsicle --colors=20 .\yige\3790685_0_final.png.750x750.gif -o .\yige\a.gif
    # 微信致谢图
    for file in os.listdir(f"{yige}"):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x==1024:
                print(file)
                base = im.copy().resize((750,750)).convert('RGB')
                base.save(f"{yige}\\{file}.750x750.gif")
                os.system(f"gifsicle --colors=16 {yige}\\{file}.750x750.gif -o {yige}\\{file}.750x750.small.gif")
                # break #一个不一定够
    
    # 微信表情包
    for i,file in enumerate(os.listdir(f"{face}")):
        idx = str(i+1).zfill(2)
        with Image.open(f"{face}\\{file}") as im:
            x,y = im.size
            if x==240:
                print(file)
                base = im.copy().convert('RGB')
                base.save(f"{facewx}\\{idx}.gif")
                base = im.copy().resize((120,120)).convert('RGBA')
                base.save(f"{facewxs}\\{idx}.png")


def collect2(name):
    n = len(os.listdir(f"{facewx}"))
    for i in range(n):
        idx = str(i+1).zfill(2)
        os.makedirs(f"{bak}\\{name}\\表情",exist_ok=True)
        os.makedirs(f"{bak}\\{name}\\缩略",exist_ok=True)
        shutil.copyfile(f"{facewx}\\{idx}.gif",f"{bak}\\{name}\\表情\\{idx}.gif") #表情
        shutil.copyfile(f"{facewxs}\\{idx}.png",f"{bak}\\{name}\\缩略\\{idx}.png") #表情缩略图
    shutil.copyfile(f"{yige}\\Face240x240.png_no-bg.png",f"{bak}\\{name}\\表情封面图.png") #表情封面图240
    shutil.copyfile(f"{yige}\\Face50x50.png_no-bg.png",f"{bak}\\{name}\\聊天页图标.png") #聊天面板图标50
    
    os.makedirs(f"{bak}\\{name}\\原图",exist_ok=True)
    for i,file in enumerate(os.listdir(f"{yige}")) :
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if not ("750x" in file or "Face" in file):
                base = im.copy()
                base.save(f"{bak}\\{name}\\原图\\{file}")
    os.makedirs(f"{bak}\\{name}\\原图表情",exist_ok=True)
    for i,file in enumerate(os.listdir(f"{face}")) :
        with Image.open(f"{face}\\{file}") as im:
            x,y = im.size
            base = im.copy()
            base.save(f"{bak}\\{name}\\原图表情\\{file}")
    #微信封面图
    for file in os.listdir(f"{yige}"):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x==750 and y==400:
                base = im.copy().convert('RGB')
                base.save(f"{bak}\\{name}\\详情页.jpg")
    # 微信引导图
    for file in os.listdir(f"{yige}"):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x==750 and y==560 and ("750x560.small" in file):
                base = im.copy().convert('RGB')
                base.save(f"{bak}\\{name}\\引导图.gif")
    # 微信致谢图
    for file in os.listdir(f"{yige}"):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x==750 and y==750 and ("750x750.small" in file):
                base = im.copy().convert('RGB')
                base.save(f"{bak}\\{name}\\致谢图.gif")
    small_intro_thanks()

def small_intro_thanks():
    # 体积太大再压一次
    import os
    intro_size = os.path.getsize(f"{bak}\\{name}\\引导图.gif")
    thanks_size = os.path.getsize(f"{bak}\\{name}\\致谢图.gif")
    print(intro_size//1024, thanks_size//1024)
    if intro_size//1024>100 or thanks_size//1024>200:
        shutil.copyfile(f"{bak}\\{name}\\引导图.gif",f"{bak}\\{name}\\intro.gif")
        shutil.copyfile(f"{bak}\\{name}\\致谢图.gif",f"{bak}\\{name}\\thanks.gif")
        os.system(f'gifsicle --colors=16 "{bak}\\{name}\\intro.gif" -o "{bak}\\{name}\\intro.small.gif"')
        os.system(f'gifsicle --colors=16 "{bak}\\{name}\\thanks.gif" -o "{bak}\\{name}\\thanks.small.gif"')
        shutil.copyfile(f"{bak}\\{name}\\intro.small.gif",f"{bak}\\{name}\\引导图.gif")
        shutil.copyfile(f"{bak}\\{name}\\thanks.small.gif",f"{bak}\\{name}\\致谢图.gif")
        os.remove(f"{bak}\\{name}\\intro.small.gif")
        os.remove(f"{bak}\\{name}\\thanks.small.gif")
        os.remove(f"{bak}\\{name}\\intro.gif")
        os.remove(f"{bak}\\{name}\\thanks.gif")


def png_face():
    # png抠图
    # 两个透明方图 表情封面图240 聊天面板图标50 ，现在可用removebg了
    if os.path.exists(f"{yige}\\Face240x240.png_no-bg.png"):
        return
    for i,file in enumerate(os.listdir(f"{yige}")):
        with Image.open(f"{yige}\\{file}") as im:
            x,y = im.size
            if x==1024 or x==512:
                print(file)
                # # 选特定的图
                # if "6863015_0_final" not in file:
                #     continue
                base = im.copy().resize((240,240)).convert('RGBA')
                base.save(f"{yige}\\Face240x240.png") 
                removebg(f"{yige}\\Face240x240.png")
                with Image.open(f"{yige}\\Face240x240.png_no-bg.png") as im2:
                    base = im2.copy().resize((50,50)).convert('RGBA')
                    base.save(f"{yige}\\Face50x50.png_no-bg.png")
                break

def png_face_by(file='3cbe6bcdef7991014ed30ebe5ae489b7.png'):
    if os.path.exists(f"{yige}\\Face240x240.png_no-bg.png"):
        return 
    with Image.open(f"{yige}\\{file}") as im:
        x,y = im.size
        if x==1024 or x==512:
            print(file)
            base = im.copy().resize((240,240)).convert('RGBA')
            base.save(f"{yige}\\Face240x240.png") 
            removebg(f"{yige}\\Face240x240.png")
            with Image.open(f"{yige}\\Face240x240.png_no-bg.png") as im2:
                base = im2.copy().resize((50,50)).convert('RGBA')
                base.save(f"{yige}\\Face50x50.png_no-bg.png")

# 基于backgroundremover，还未开始使用
def png_face_by2(file='828476ab3f5655b020667125df90eedd.png'):
    if os.path.exists(f"{yige}\\Face240x240.nobg.png"):
        return 
    with Image.open(f"{yige}\\{file}") as im:
        x,y = im.size
        if x==1024 or x==512:
            print(file)
            base = im.copy().resize((240,240)).convert('RGBA')
            base.save(f"{yige}\\Face240x240.png") 
            filename = f"{yige}\\Face240x240.png"
            os.system(f'backgroundremover -i "{filename}" -o "{yige}\\Face240x240.nobg.png"')
            with Image.open(f"{yige}\\Face240x240.nobg.png") as im2:
                base = im2.copy().resize((50,50)).convert('RGBA')
                base.save(f"{yige}\\Face50x50.nobg.png")

def clean_wxface():
    # 清除表情包
    shutil.rmtree(f"{facewx}")
    shutil.rmtree(f"{facewxs}")
    os.makedirs(f"{facewx}")
    os.makedirs(f"{facewxs}")
    for  f in os.listdir(f"{yige}"):
        if "750x" in f or "Face" in f: # 中间步骤的图
            os.remove(f"{yige}\\{f}")

def clean_face_all():
    # 清除表情包
    shutil.rmtree(f"{face}")
    shutil.rmtree(f"{yige}")
    os.makedirs(f"{face}")
    os.makedirs(f"{yige}")
    clean_wxface()


def removebg(path="tmp\\yige\\6863015_0_final.png"):
    # https://www.remove.bg/api#sample-code
    import requests

    response = requests.post(
        'https://api.remove.bg/v1.0/removebg',
        files={'image_file': open(path, 'rb')},
        data={'size': 'auto'},
        headers={'X-Api-Key': 'LagCfzHzCJj7xzizrNkuGSap'},
    )
    if response.status_code == requests.codes.ok:
        with open(f'{path}_no-bg.png', 'wb') as out:
            out.write(response.content)
    else:
        print("Error:", response.status_code, response.text)

import app.face.face8pic as face8pic
def one_pic(line="好无聊"):
    for  file in os.listdir(f"tmp\\demo"):
        face8pic.convert(f"tmp\\demo\\{file}",line)
        pngfile = file.replace(".jpg",f".png").replace(".png",f".{line}.png")
        giffile = file.replace(".jpg",f".png").replace(".png",f".{line}.gif")
        with Image.open(f"tmp\\demo\\{pngfile}") as im:
            base = im.copy().convert('RGB')
            base.save(f"tmp\\demo\\{giffile}")
        os.makedirs(f"{bak}\\单品-{line}",exist_ok=True)
        shutil.copyfile(f"tmp\\demo\\{file}",f"{bak}\\单品-{line}\\{file}") #表情原图
        shutil.copyfile(f"tmp\\demo\\{giffile}",f"{bak}\\单品-{line}\\{giffile}") #表情   
        shutil.copyfile(f"tmp\\demo\\{pngfile}",f"{bak}\\单品-{line}\\{pngfile}") #表情缩略图
        os.remove(f"tmp\\demo\\{file}")
        os.remove(f"tmp\\demo\\{giffile}")
        os.remove(f"tmp\\demo\\{pngfile}")
        

if __name__ == '__main__':
    # one_pic("驶向春天")
    # png_face_by('GBMPvqhGvEeYyXPtF8QEFqzPBOAXcwmF-0.jpg')
    
    name = "白羊座2"
    import questionary
    s=questionary.select("做什么?",choices=["生成","收集","清除"]).ask()
    if s == "生成":
        generate_wxface()
        png_face()
    elif s == "收集":
        collect2(name)
    else:
        clean_face_all()
    pass
